<template>
      <div class="app-container">
            <div class="filter-container">
                  <el-input style="width: 200px;" class="filter-item" placeholder="请输入账号组名称" @keyup.enter.native="handleFilter" v-model="listQuery.departName">
                  </el-input>
                  <el-button class="filter-item" type="primary" icon="search" @click="handleFilter">
                        搜索
                  </el-button>
                  <el-button class="filter-item" style="float:right" type="default" icon="edit" @click="handleCreate">
                        新建账号组
                  </el-button>
            </div>
            <el-table :data="tableData" v-loading.body="listLoading" border fit highlight-current-row style="width: 100%">
      
                  <el-table-column align="center" label="序号" min-width="65">
                        <template scope="scope">
                              <span>{{scope.$index+1+(listQuery.page-1)*listQuery.limit}}</span>
                        </template>
                  </el-table-column>
      
                  <el-table-column min-width="250" align="left" label="帐号组名称">
                        <template scope="scope">
                              <span>{{scope.row.departName}}</span>
                        </template>
                  </el-table-column>
      
                  <el-table-column min-width="250" label="所在企业">
                        <template scope="scope">
                              <span>{{scope.row.companyName}}</span>
                        </template>
                  </el-table-column>
      
                  <el-table-column width="150" label="包含账号">
                        <template scope="scope">
                              <span>{{scope.row.accountCount}}</span>
                        </template>
                  </el-table-column>
      
                  <el-table-column width="150" label="对应角色">
                        <template scope="scope">
                              <span>{{scope.row.roleCount}}</span>
                        </template>
                  </el-table-column>
      
                  <el-table-column label="操作" width="150">
                        <template scope="scope">
                              <el-button size="small" type="success" @click="handleUpdate(scope.row)">
                                    编辑
                              </el-button>
                              <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                                    删除
                              </el-button>
                        </template>
                  </el-table-column>
            </el-table>
            <div v-show="!listLoading" class="pagination-container">
                  <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
                  </el-pagination>
            </div>
            <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" style='margin-top:50px;' size="tiny">
                  <el-form :model="temp" :rules="rules" ref="temp">
      
                        <el-form-item label="所属企业" :label-width="formLabelWidth" prop="companyId">
                              <el-select v-model="temp.companyId" placeholder="请选择所属企业" :style="inputWidth" :disabled="temp.disabled" @change="selectEnterprise">
                                    <el-option v-for="enterprise in enterpriseList" :key="enterprise.companyId" :label="enterprise.companyName" :value="String(enterprise.companyId)"></el-option>
                              </el-select>
                        </el-form-item>
      
                        <el-form-item label="帐号组名" prop="departName" :label-width="formLabelWidth">
                              <el-input v-model="temp.departName" auto-complete="off" :style="inputWidth" :maxlength="maxlength"></el-input>
                        </el-form-item>
      
                        <el-form-item label="角色配置" :label-width="formLabelWidth">
                              <el-button size="small" @click="handleCheckAllChange">全选</el-button>
                              <el-button size="small" @click="handleCancelAllChange">全不选</el-button>
                              <div style="margin: 15px 0;"></div>
                              <el-checkbox-group v-model="checkedRoles">
                                    <el-checkbox v-for="role in roles" :label="role" :key="role">{{role}}</el-checkbox>
                              </el-checkbox-group>
                        </el-form-item>
      
                  </el-form>
                  <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogFormVisible = false">取 消</el-button>
                        <el-button type="primary" @click="create">确 定</el-button>
                  </div>
            </el-dialog>
      </div>
</template>
<script>
export default {
      data() {
            return {
                  tableData: null,
                  list: null,
                  listCopy: null,
                  total: null,
                  listLoading: true,
                  listQuery: {
                        page: 1,
                        limit: 10,
                        departName: ''
                  },
                  dialogFormVisible: false,
                  dialogStatus: '',
                  temp: {
                        departName: '',
                        departId: '',
                        companyName: '',
                        companyId: '',
                        disabled: false,
                  },
                  enterpriseList: {
                        companyName: '',
                        companyId: '',
                  },
                  textMap: {
                        update: '编辑账号组信息',
                        create: '新建账号组信息'
                  },
                  inputWidth: {
                        width: '90%'
                  },
                  formLabelWidth: '100px',
                  rules: {
                        companyId: [
                              { required: true, message: '请选择企业名称', trigger: 'change' }
                        ],
                        departName: [
                              { required: true, message: '请输入帐号组名', trigger: 'blur' }
                        ]
                  },

                  rolelist: [],
                  checkedRoles: [],
                  roles: [],
                  maxlength: 50
            }
      },
      created() {
            this.getList();
      },
      methods: {
            getList() {
                  this.listLoading = true;
                  this.$http.get('/sys/depart/allDeparts')
                        .then((response) => {
                              if (response.code === 0) {
                                    //如果页面跳转有传参，过滤数据
                                    let role_id = this.$route.query.id;
                                    if (role_id !== undefined) {
                                          this.list = response.data.filter((item) => {
                                                return item.roles.some(elem => {
                                                      return role_id === elem.roleId
                                                })
                                          });
                                    } else {
                                          this.list = response.data;
                                    }
                                    this.listCopy = this.list;
                                    this.total = this.list.length;
                                    //
                                    this.listLoading = false;
                                    this.pageChange(this.listQuery.page);
                                    // console.log(this.list);
                              }
                        })
                        .catch(function (response) {
                              console.log(response);
                        })
            },
            //搜索筛选
            handleFilter() {
                  this.listCopy = this.list.filter(item => {
                        return item.departName.indexOf(this.listQuery.departName) > -1;
                  });
                  // console.log(this.listCopy);
                  this.total = this.listCopy.length;
                  this.pageChange(this.listQuery.page);
            },
            //以下，分页函数
            handleSizeChange(val) {
                  this.listQuery.limit = val;
                  this.pageChange(this.listQuery.page);
            },
            handleCurrentChange(val) {
                  this.listQuery.page = val;
                  this.pageChange(val);
            },
            pageChange(page) {
                  this.tableData = this.listCopy.slice((page - 1) * this.listQuery.limit, page * this.listQuery.limit);
            },
            //新建信息，弹对话框
            handleCreate() {
                  this.getEnterpriseList();
                  this.resetTemp();
                  this.checkedRoles = [];
                  this.roles = [];
                  this.dialogStatus = 'create';
                  this.dialogFormVisible = true;
            },
            //编辑信息
            handleUpdate(row) {
                  // console.log(row);
                  this.getEnterpriseList();
                  if (this.$refs['temp']) {
                        this.$refs['temp'].resetFields();
                  }
                  this.checkedRoles = [];
                  this.roles = [];
                  var url = '/sys/depart/role/' + row.companyId;
                  this.$http.get(url)
                        .then((response) => {
                              if (response.code === 0) {
                                    this.rolelist = response.data;
                                    this.rolelist.forEach((item) => {
                                          this.roles.push(item.roleName);

                                    });
                                    // console.log(this.roles);
                              } else {
                                    console.log(response.msg);
                              }
                        })
                  row.roles.forEach((item) => {
                        this.checkedRoles.push(item.roleName);
                  });
                  this.temp = Object.assign({}, row);
                  this.dialogStatus = 'update';
                  this.temp.disabled = true;
                  this.dialogFormVisible = true;
            },
            //删除信息
            handleDelete(row) {
                  // console.log(row);
                  const h = this.$createElement;
                  var message = '';
                  if (row.accountCount > 0) {
                        message = h('p', null, '该账号组下包含了' + row.accountCount + '个账号，删除账号组会导致这些账号随之删除，是否继续？');
                  } else {
                        message = h('p', null, [h('span', null, '是否删除 '), h('span', { style: 'color: #f00' }, row.departName), h('span', null, ' 这个账号组')]);
                  }
                  var url = '/sys/depart/' + row.companyId + '/' + row.departId;
                  this.$msgbox({
                        title: '删除账号组',
                        message: message,
                        showCancelButton: true,
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                  }).then((action) => {
                        if (action === 'confirm') {
                              this.$http.delete(url)
                                    .then((response) => {
                                          if (response.code === 0) {
                                                this.showMessage("删除成功!", "success");
                                                this.getList();
                                          } else if (response.code === 80) {

                                                this.$confirm('该账号组所属的企业已被锁定，请联系管理员进行解锁', '无法操作该账号组', {
                                                      confirmButtonText: '确定',
                                                      showCancelButton: false,
                                                      type: 'error'
                                                }).then(() => {
                                                      this.dialogFormVisible = false;
                                                })
                                          } else {
                                                console.log(response.msg);
                                                this.showMessage('系统错误!', 'error');
                                          }
                                    })
                                    .catch(function (response) {
                                          console.log(response)
                                    })
                        } else {
                              this.showMessage('已取消更改!', 'info');
                        }
                  }).catch(() => {
                        this.showMessage('已取消删除!', 'info');
                  });
            },
            //确认新建信息
            create() {
                  // console.log(this.temp);
                  // console.log(this.checkedRoles);
                  var url = '';
                  var selectRoles = [];
                  this.$refs['temp'].validate((valid) => {
                        if (valid) {
                              if (this.dialogStatus === 'create') {
                                    this.checkedRoles.forEach((item) => {
                                          // console.log(item);
                                          this.rolelist.forEach((n) => {
                                                if (item === n.roleName) {
                                                      selectRoles.push({
                                                            roleName: n.roleName,
                                                            roleId: n.roleId
                                                      })
                                                }
                                          });
                                    });
                                    // console.log(selectRoles);
                                    url = '/sys/depart';
                                    this.$http.post(url, {
                                          "companyId": this.temp.companyId,
                                          "departName": this.temp.departName,
                                          "roles": selectRoles,
                                    })
                                          .then((response) => {
                                                console.log(response);
                                                if (response.code === 0) {
                                                      this.dialogFormVisible = false
                                                      this.showMessage('创建成功!', 'success');
                                                      this.getList();
                                                } else if (response.code === 80) {

                                                      this.$confirm('该账号组所属的企业已被锁定，请联系管理员进行解锁', '无法操作该账号组', {
                                                            confirmButtonText: '确定',
                                                            showCancelButton: false,
                                                            type: 'error'
                                                      }).then(() => {
                                                            // this.dialogFormVisible = false;
                                                      })
                                                } else {
                                                      this.dialogFormVisible = false
                                                      console.log(response.msg);
                                                      this.showMessage('系统错误!', 'error');
                                                }
                                          }).catch((response) => {
                                                console.log(response);
                                          })
                              } else {
                                    this.checkedRoles.forEach((item) => {
                                          // console.log(item);
                                          this.rolelist.forEach((n) => {
                                                if (item === n.roleName) {
                                                      selectRoles.push({
                                                            roleName: n.roleName,
                                                            roleId: n.roleId
                                                      })
                                                }
                                          });
                                    });
                                    url = '/sys/depart';
                                    this.$http.put(url, {
                                          "companyId": this.temp.companyId,
                                          "departId": this.temp.departId,
                                          "departName": this.temp.departName,
                                          "roles": selectRoles,
                                          "useTag": this.temp.useTag
                                    })
                                          .then((response) => {
                                                if (response.code === 0) {
                                                      this.dialogFormVisible = false;
                                                      this.showMessage('修改成功!', 'success');
                                                      this.getList();
                                                } else if (response.code === 80) {

                                                      this.$confirm('该账号组所属的企业已被锁定，请联系管理员进行解锁', '无法操作该账号组', {
                                                            confirmButtonText: '确定',
                                                            showCancelButton: false,
                                                            type: 'error'
                                                      }).then(() => {
                                                            this.dialogFormVisible = false;
                                                      })
                                                } else {
                                                      this.dialogFormVisible = false;
                                                      console.log(response.msg);
                                                      this.showMessage('系统错误!', 'error');
                                                }
                                          }).catch((response) => {
                                                console.log(response);
                                          })
                              }
                        } else {
                              console.log('error submit!!');
                              return false;
                        }
                  });
            },
            //置空temp数据，防止绑定信息
            resetTemp() {
                  if (this.$refs['temp']) {
                        this.$refs['temp'].resetFields();
                  }

                  this.temp = {
                        departName: '',
                        departId: '',
                        companyName: '',
                        companyId: '',
                        disabled: false
                  };
            },
            //上方提示消息
            showMessage(msg, type) {
                  this.$message({
                        message: msg,
                        type: type
                  });
            },
            //多选框
            handleCheckAllChange() {
                  this.checkedRoles = this.roles;
            },
            handleCancelAllChange() {
                  this.checkedRoles = [];
            },
            //获取企业列表下拉框
            getEnterpriseList() {
                  this.$http.get('/sys/company/alllist')
                        .then((response) => {
                              if (response.code === 0) {
                                    // console.log(response.data);
                                    this.enterpriseList = response.data;
                              } else {
                                    console.log(response.msg);
                              }
                        }).catch((response) => {
                              console.log(response);
                        })
            },
            //选择企业变化角色事件
            selectEnterprise(val) {
                  this.roles = [];
                  var url = '/sys/depart/role/' + val;
                  if (this.temp.disabled === false && val != '') {
                        this.$http.get(url)
                              .then((response) => {
                                    console.log(response.code);
                                    if (response.code === 0) {
                                          this.rolelist = response.data;
                                          // console.log(this.rolelist);
                                          if (this.rolelist.length === 0) {
                                                this.$confirm('该企业内还没有任何角色，请先新建角色再新建账号组', '无法新建帐号组', {
                                                      confirmButtonText: '确定',
                                                      showCancelButton: false,
                                                      type: 'error'
                                                }).then(() => {
                                                      this.temp.companyId = '';
                                                }).catch(() => {
                                                });
                                          } else {
                                                this.rolelist.forEach((item) => {
                                                      this.roles.push(item.roleName);
                                                });
                                          }
                                    } else {
                                          console.log(response.msg);
                                    }
                              }).catch((response) => {
                                    console.log(response);
                              })
                  }
            }
      }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.filter-container {
      padding-bottom: 10px;
      .filter-item {
            margin-bottom: 10px;
      }
}

.pagination-container {
      margin-top: 30px;
}
</style>